<template>
  <div
    class="w-400px absolute top-0 z-10 text-#fff h-95% bg-#00313780"
    v-if="monitorial.show"
  >
    <div class="flex justify-between items-center">
      <el-autocomplete
        v-model="state"
        :loading="loading"
        width="80%"
        loading-text="搜索中..."
        :fetch-suggestions="querySearchAsync"
        placeholder="Please input"
        @select="handleSelect"
      />
      <div class="text-20px text-#fff" @click="close">X</div>
    </div>
    <div class="h-97% overflow-y-auto w-full items">
      <div
        v-for="(item, index) in monitorTableList"
        :key="index"
        class="detail-item p-0.3"
        @click="handleSelect(item)"
      >
        {{ index }} : {{ item.deviceName }}
      </div>
    </div>
  </div>
  <!-- 展开收起 -->
  <img
    v-show="monitorial.showArrow"
    :class="[
      'absolute top-2px z-[10] w-30px h-30px ',
      monitorial.show ? 'left-400px' : 'rotate-180 left-0',
    ]"
    @click="monitorial.show = !monitorial.show"
    :src="getAssets('home/arrow-1.png')"
    alt="展开监控列表"
  />

  <VideoPlayer
    v-if="showVideo"
    @closeVideo="showVideo = false"
    :source="video.source"
    :info="video.info"
  />
</template>


<script lang="ts" setup>
import { useMonitorTableList, useBoolean } from "@/store";
import { getAssets, jianKongUrl } from "@/utils";
import { GetSearchMonitoring } from "@/service/api/map";

const worker = new Worker(
  new URL("../../workers/mapDataWorker.ts", import.meta.url),
  { type: "module" }
);

interface MonitorTableList {
  deviceId: string;
  deviceName: string;
  jd: string;
  value: string;
  wd: string;
}

const monitorial = useMonitorTableList();
const { setState } = useBoolean();
const monitorTableList = ref<MonitorTableList[]>([]);
const showVideo = ref(false);
const video = reactive<any>({
  info: null,
  source: "",
});
watch(
  () => monitorial.show,
  (newVal) => {
    monitorTableList.value = monitorial.data || []; // 兜底空数组
    if (newVal) {
      setState(false);
      monitorial.setShowArrow(true);
    }
  }
);

interface WorkerResponse {
  type: "batch" | "complete";
  data: Array<{ position: string; image: string }> | number;
}

// 监听 Worker 消息
worker.addEventListener("message", (e: MessageEvent<WorkerResponse>) => {
  const { type, data } = e.data;
  const { primitiveLoader } = window.cesiumInit;
  if (type === "batch") {
    const image = getAssets(data[0].image + "Marker.png");
    // 处理每一批数据
    (data as Array<{ position: string; image: string }>).forEach((item) => {
      if (item.image === "construction") {
        primitiveLoader.addPrimitiveLayer(item.position);
      }
      primitiveLoader.addPointPrimitive(item.position, image, {
        ...item,
        type,
      });
    });
  } else if (type === "complete") {
    console.log(`处理完成，共处理 ${data} 条数据`);
  }
});

const state = ref("");
const loading = ref(false);
const oldSearch = ref("");
const monitorialList = ref<MonitorTableList[]>();
const querySearchAsync = (
  queryString: string,
  cb: (arg: any) => void
  // type: string = "monitor"
) => {
  // 当查询字符串为空时直接返回且不执行任何操作
  if (!queryString.trim()) {
    cb([]); // 清空建议列表
    return;
  }
  if (queryString === oldSearch.value) {
    cb(monitorialList.value);
    return;
  }
  // const { primitiveLoader, draw } = window.cesiumInit;

  // primitiveLoader.clearAllMapLayers();
  // draw.removeAll();
  loading.value = true;

  (async () => {
    try {
      const res = await GetSearchMonitoring(queryString);
      // monitorTablelist.value = res;
      // 直接展示所有结果
      const results = res.map((item) => ({
        value: item.deviceName,
        ...JSON.parse(JSON.stringify(item)), // 深拷贝
      }));
      monitorialList.value = results;
      oldSearch.value = queryString;
      cb(results);
    } catch (err) {
      console.error("搜索失败:", err);
      cb([]); // 异常时清空建议列表
    } finally {
      loading.value = false;
    }
  })();
};

const close = () => {
  const { primitiveLoader, draw } = window.cesiumInit;
  primitiveLoader.clearAllMapLayers();
  draw.removeAll();
  monitorial.setState(false, "", []);
  monitorial.setShowArrow(false);
};

// 选项选择处理函数
const handleSelect = async (item: Record<string, any>) => {
  const res = await jianKongUrl(item.deviceId);
  if (res) {
    showVideo.value = true;
    video.source = res;
    video.info = item;
  }
};
</script>



<style  scoped>
.el-autocomplete__popper.el-popper,
.el-autocomplete__popper.el-popper .el-popper__arrow:before {
  background: rgba(2, 121, 249, 0.2);
  display: none;
}
.el-autocomplete__popper.el-popper > * {
  border: none;
}
/* 在样式部分添加 */
.items::-webkit-scrollbar {
  display: none; /* Chrome/Safari */
}
.detail-item:hover {
  background: rgba(2, 121, 249, 0.3);
  color: skyblue;
}
.el-autocomplete-suggestion li {
  color: white;
}
.el-autocomplete-suggestion li:hover {
  color: black;
}
</style>
